#include <thermalcontroller.h>
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <filesystem>
#include <regex>

ThermalController::ThermalController() {}

ThermalController::~ThermalController() {}

void ThermalController::findThermalPath()
{
    // CPU传感器常见类型
    std::vector<std::string> cpu_sensor_types = {"Processor", "CPU", "Package"};

    const std::string thermal_base_path = "/sys/class/thermal";

    // 遍历所有thermal_zone目录
    for (const auto &entry : std::filesystem::directory_iterator(thermal_base_path))
    {
        if (!entry.path().string().find("/thermal_zone"))
        {
            continue;
        }

        // 检查传感器类型
        std::ifstream type_file(entry.path() / "type");
        std::string sensor_type;
        if (type_file >> sensor_type)
        {
            // 检查是否为目标传感器类型
            for (const auto &target_type : cpu_sensor_types)
            {
                if (sensor_type.find(target_type) != std::string::npos)
                {
                    // 判断是否有温度文件
                    if (!std::filesystem::exists(entry.path() / "temp"))
                    {
                        continue;
                    }
                    cpuThermalPath = entry.path() / "temp";
                }
            }
        }
    }

    std::string hwmon_base_path = "/sys/class/hwmon";
    for (const auto &entry : std::filesystem::directory_iterator(hwmon_base_path))
    {
        std::string hwmonPath = entry.path();

        // 遍历temp[0-9]+_label文件
        for (const auto &entry : std::filesystem::recursive_directory_iterator(hwmonPath))
        {
            if (std::regex_match(entry.path().filename().string(),
                                 std::regex("temp[0-9]+_label")))
            {
                std::ifstream labelFile(entry.path());
                std::string sensorLabel;
                if (labelFile >> sensorLabel)
                {
                    for (const auto &target_type : cpu_sensor_types)
                    {
                        if (sensorLabel.find(target_type) != std::string::npos)
                        {
                            for (const auto &entry : std::filesystem::recursive_directory_iterator(hwmonPath))
                            {
                                if (std::regex_match(entry.path().filename().string(),
                                                     std::regex("temp[0-9]+_input")))
                                {
                                    cpuThermalPath = entry.path();
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}

float ThermalController::getCpuTemp() const
{
    // 读取温度值
    std::ifstream temp_file(cpuThermalPath);
    int temp_millicelsius;
    if (temp_file >> temp_millicelsius)
    {
        return temp_millicelsius / 1000.0f; // 转换为摄氏度
    }
    else
    {
        return -1;
    }
}
